<template>
	<view class="xylink-container">
		<view>
			<!-- 会议操作条 -->
			<view>
				<view class="xylink-operate-box xylink-operate-left">
					<view>已通话:{{ callTimeText }}</view>
					<view @tap="onSwitchPosition" class="">
						<!-- {{ devicePosition === "front" ? "前置" : "后置" }} -->
						切换摄像头
					</view>
					<view @tap="onChangeMuted" class="">{{ muted ? "取消静音" : "静音" }}</view>
					<view @tap="onSwitchCamera" class="">{{ camera ? "关闭视频" : "开启视频" }}</view>
					<view @tap="onStopMeeting" class="">挂断</view>
				</view>
			</view>

			<!-- 小鱼小程序SDK UI组件 -->
			<xylink-room
				:template="template"
				:beauty="6"
				:muted="muted"
				:camera="camera"
				:devicePosition="devicePosition"
				id="xylink"
			/>
		</view>

		<u-modal
			:show="coloseShow"
			width="295px"
      title="温馨提示"
			content="当前服务还在进行中,是否离开?"
			:showCancelButton="true"
			@cancel="coloseShow = false"
			@confirm="sureStopMeeting"
		></u-modal>

    <u-modal
			:show="disconnectedShow"
      ref="disconnectedModal"
			width="295px"
      title="网络异常"
			content="网络已断开,请检查网络连接状态后再重新连接"
      :asyncClose="true"
      confirmText="重新连接"
			@confirm="reconnection"
		></u-modal>
	</view>
</template>

<script>
import xylinkRoom from "./components/index.vue";
import XYRTC from "@/utils/xy/xy-mp-sdk";

export default {
	components: {
		xylinkRoom,
	},
	computed: {
		// 用户信息
		userInfo() {
			return this.$store.state.userInfo;
		},
		// 小鱼会议信息
		cellInfo() {
			return this.$store.state.cellInfo;
		},
		// 当前通话IM对象
		currentMessage() {
			return this.$store.state.currentMessage;
		},
	},
	watch: {
		detailLength(nval, oval) {
      console.log(`现在${nval}人,之前${oval}人`);
			if (oval > 1 && nval === 1) {
				// 通话后,只剩下自己一人
				this.constSetTimeout = setTimeout(() => { this.sureStopMeeting() }, 20000);
			}else{
        clearTimeout(this.constSetTimeout);
        this.constSetTimeout = null;
      }
		},
	},
	data() {
		return {
			xy_userInfo: {}, // 自己的小鱼用户信息
			// 麦克风状态
			muted: false,
			// 摄像头状态
			camera: true,
			// 前/后置摄像头
			devicePosition: "front",
			// 此处没有读取设置页面的值，是因为小程序data值会全局缓存，退出在进入后仍然获取上一次的值，解决办法是在onLoad上重新赋值
			// 指定SDK UI布局模式，可选auto：自动布局 ｜ custom：自定义布局
			template: {
				layout: "auto",
				detail: [],
			},
			displayName: "",

			coloseShow: false,
			callTime: 0, // 通话时间
			callTimeText: "", // 通话时间
			callTimeFn: "", // 通话时间定时器
			detailLength: 0, // 当前显示的用户数量
      constSetTimeout: null,
      disconnectedShow: false,
		};
	},
	onLoad() {
		this.xyInit(); // 初始化小鱼
	},
	async onReady() {
		await this.xyCell(); // 房间呼叫
	},
	onUnload() {
		this.callTimeFn = "";
		clearTimeout(this.callTimeFn);
	},

	methods: {
		// 小鱼初始化
		xyInit() {
			this.xy_userInfo = uni.getStorageSync("xy_userInfo");
			const layoutMode = uni.getStorageSync("XY_LAYOUT_MODE") || "auto";
			this.template.layout = layoutMode;
			this.displayName = this.userInfo.userName || "无名";

			this.XYClient = XYRTC.createClient({
				// 配置画面容器偏移量：上：0px，下：40px，左右：0px
				// 目的是排除底部40px空间，显示操作条
				container: {
					offset: [0, 40, 0, 0],
				},
			});

			// 自定义布局，设置初始本地Local预览画面和启动推流
			if (layoutMode === "custom") {
				// 初始页面加载时，获取本地Local数据，做首屏展示
				this.setData({
					template: {
						layout: layoutMode,
						detail: [
							{
								// 最终转换为x: 0vw, y: 0vh, width: 100vw, height: 85vh
								position: [0, 0, 100, 85],
								callNumber: this.xy_userInfo.callNumber,
								name: this.userInfo.userName || "无名",
								quality: "normal",
								isContent: false,
							},
						],
					},
				});
			}

			this.XYClient.on("roomEvent", (e) => {
				console.log(e, "小鱼事件");
				// 详细type定义见Type列表
				const { type, detail } = e;
				if (type === "layout") {
					this.detailLength = detail.length;
				}else if(type === "disconnected" && detail.code === "ROOM_EXIT"){
          this.disconnectedShow = true;
        }else if(type === 'connecting' && detail.code === 302) {
          uni.showToast({
            title: '房间不存在,请重新呼叫',
            icon: 'none'
          })
        }
			});
		},
    // 网络异常,小鱼主动挂断会议,检查网络后重新进入页面连接会议
    reconnection() {
      const that = this;
      uni.getNetworkType({
        success (res) {
          const networkType = res.networkType;
          if(networkType !== 'none'){
            that.disconnectedShow = false;
            uni.redirectTo({ url: `/pagesB/meeting/index` });
          }else{
            setTimeout(() => {
              that.$refs.disconnectedModal.loading = false;
            }, 2000);
          }
        }
      })
    },

		// 房间呼叫方法
		async xyCell() {
			const { meetingRoomNumber, password } = this.cellInfo;
			// 发起SDK呼叫，通过回调获取结果
			const { code } = await this.XYClient.makeCall({
				number: meetingRoomNumber,
				password: password,
				displayName: this.userInfo.userName || "无名",
				isAudioMute: false,
				isVideoMute: false,
				cameraPosition: this.devicePosition,
			});
			if (code !== 200) {
				// 呼叫失败,退出呼叫页面
				uni.navigateBack({ delta: 1 });
			} else {
				console.log("呼叫成功",this.currentMessage);
				this.startTime(); // 开始通话计时
				this.$store.dispatch("reportStatus", {
					status: 2,
					orderNo: this.cellInfo.orderNo,
					groupId: this.currentMessage.data.imGroupId,
				});
			}
		},
		// 切换前后置摄像头
		async onSwitchPosition() {
			const position = await this.XYClient.switchCamera();
			this.devicePosition = position;
		},
		//  开启/关闭麦克风
		onChangeMuted() {
			this.muted = !this.muted;
		},
		//  开启/关闭摄像头
		onSwitchCamera() {
			this.camera = !this.camera;
		},
		// 挂断
		onStopMeeting() {
			this.coloseShow = true;
		},
		// 挂断事件
		sureStopMeeting() {
			const that = this;
			if (that.currentMessage.data) {
				// evtImMsgHostAllEndOfCall: 自己是主持人;
				// evtImMsgMemberAllEndOfCall: 两人通话
				// 否则: evtImMsgHostMemberEndOfCall
				let action =
					that.currentMessage.data.hostId == that.userInfo.id
						? "evtImMsgHostAllEndOfCall"
						: that.detailLength === 2
						? "evtImMsgMemberAllEndOfCall"
						: "evtImMsgHostMemberEndOfCall";
				that.$store.dispatch("sendMessage", {
					groupID: that.currentMessage.data.imGroupId,
					action,
					replyMsg: that.currentMessage,
				});
			}
			// 挂断会议
			that.XYClient.hangup();
			that.currentMessage.data.hostId == that.userInfo.id
				? uni.redirectTo({url: `/pagesC/order/orderDetails?orderNo=${that.cellInfo.orderNo}`})
				: that.goBack();
			setTimeout(() => {
				that.$store.commit("SET_CURRENTMESSAGE", {});
				that.$store.commit("SET_CELLINFO", {});
				that.$store.dispatch("dissolveGroup"); // 解散群组
				that.$store.dispatch("reportStatus", { status: 3 }); // 改为上线
			}, 2000);
		},
		// 通话时间计时器
		startTime() {
			if (this.callTime) return;
			this.callTimeFn = setInterval(() => {
				this.callTime = this.callTime + 1;
				let min_total = Math.floor(this.callTime / 60); // 总分钟
				let hour_total = Math.floor(min_total / 60); // 小时数
				let min = Math.floor(min_total % 60); // 余分钟
				let sec = Math.floor(this.callTime % 60); // 余秒
				this.callTimeText = `${hour_total < 10 ? "0" : ""}${hour_total}:${
					min < 10 ? "0" : ""
				}${min}:${sec < 10 ? "0" : ""}${sec}`;
			}, 1000);
		},
	},
};
</script>
<style>
.xylink-container {
	background-color: #1f1f25;
	height: 100vh;
	width: 100vw;
	color: #fff;
}

.xylink-operate-box {
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100vw;
	height: 40px;
	background-color: rgba(0, 0, 0, 0.8);

	display: flex;
	align-items: center;
	justify-content: space-around;
	font-size: 14px;
	z-index: 100;
}
</style>
